package com.kapukapu.authorization.config;

import java.io.IOException;
import java.security.Principal;
import java.util.Map;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.util.IOUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: sivan
 * @date: 2020/03/03
 * @email: zifanuu@gmail.com
 */
@FrameworkEndpoint
public class JwkEndpoint {

	@Value("${security.oauth2.public-key}")
	private String publicKey;

	@GetMapping("/.well-known/jwks.json")
	@ResponseBody
	public Map<String, Object> getKey(Principal principal) {
		RSAKey key = null;
		try {
			String pemEncodedObjects = IOUtils
					.readFileToString(ResourceUtils.getFile(publicKey));
			key = new RSAKey.Builder(
					RSAKey.parseFromPEMEncodedObjects(pemEncodedObjects).toRSAKey())
							.build();
		}
		catch (JOSEException | IOException e) {
			// 不会发生
			e.printStackTrace();
		}
		return new JWKSet(key).toJSONObject();
	}

}
